const express = require("express");
const cors = require("cors");
const userRouter = require("./router/user");
const articleRouter = require("./router/article");
const uploadRouter = require("./router/upload");
const categoryRouter = require("./router/category");
const updateRouter = require("./router/update");
const Joi = require("joi");
const config = require("./config");
const expressJWT = require("express-jwt");

const app = express();
app.use(cors());
app.use(express.urlencoded({ extended: false }));
app.use(express.json());

// 托管静态资源
app.use("/uploads", express.static("./public/uploads"));
// 全局错误级别中间件,必须在挂载路由之前定义
app.use(function (req, res, next) {
  res.cc = function (err, status = 1) {
    res.send({
      status,
      message: err instanceof Error ? err.message : err,
    });
  };
  next();
});
// 要在路由之前配置解析token 的中间件
app.use(
  expressJWT({ secret: config.jwtSecretKey }).unless({
    path: [/^\/api\//, /^\/article\//, /^\/category\//],
  })
);

app.use("/api", userRouter);
app.use("/api", uploadRouter);
app.use("/user", updateRouter);
app.use("/article", articleRouter);
app.use("/category", categoryRouter);

app.use((err, req, res, next) => {
  // 验证失败导致的错误
  if (err instanceof Joi.ValidationError) return res.cc(err);
  // 捕获身份认证失败的错误
  if (err.name === "UnauthorizedError") return res.cc("身份认证失败！");
  // 未知错误
  res.cc(err);
});
app.listen(4000, () => {
  console.log("Server is running on http://127.0.0.1:4000");
});
